package com.sloth.controller;

import com.sloth.service.ProductService;
import com.sloth.util.FileUtils;
import com.sloth.util.QiNiuUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class ImgUploadController {

    @Autowired
    private ProductService productService;

    @Value("${web.upload-path}")
    private String path;

    @Value("${server.port}")
    private String port;
    /**
     * @param file 要上传的文件
     * @return
     */

    @PostMapping("fileUpload")
    @ResponseBody
    public Map<String, String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        Map<String,String>  map=new HashMap<>();

        String filePath = request.getSession().getServletContext().getRealPath(path);

        //生成随机字符串，用于图片命名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        // 获得文件类型
        String fileType = file.getContentType();
        // 获得文件后缀名称
        String imageName = fileType.substring(fileType.indexOf("/") + 1);
        // 原名称
        String fileName = file.getOriginalFilename();
        // 新名称
        String newFileName = uuid + "." + imageName;

        System.out.println(imageName);
        String imagepath="";
        try {

//          上传到七牛云
            imagepath = QiNiuUtil.updateFile(file,fileName);
            System.out.println("imagepath: "+imagepath);
            //上传文件到本地
//            FileUtils.upload(file.getBytes(), filePath, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 拼接图片url
//        String imgHost = "http://127.0.0.1:" + port;
//        String imgUploadPath = path;
//        String imgName = newFileName;
//        String imgPath = imgUploadPath + imgName;
//        System.out.println("imgPath: "+imgPath);
//        图片地址存到数据库
//        productService.imgUpload(imgPath);

        map.put("url",imagepath);
        return map;

    }

}
